package com.waitingresult.zuo.sort;

import java.util.Arrays;

/**
 * @Author: WangShuai
 * @CreateTime: 2022-11-07  09:43
 * @Description: 二分查找
 * @Version: 1.0
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {70, 2, 12, 4, 463, 678, 8, 9, 1, 33, 6};
        System.err.println(Arrays.toString(arr));
        sort(arr);
        System.err.println(Arrays.toString(arr));
        System.out.println(find(arr, 8));
//
//        System.err.println(binarySearch(arr, 678));

    }

    public static int find(int[] arr, int targetNumber) {

        // 0,1,2,3,4,5,6,7,8,9
        // size : 10 ,target : 1
        // index : 5 ? L=0 R=5
        // index : 2 ? L=2 R=5

        // 左边界
        int L = 0;
        // 右边界
        int R = arr.length - 1;
        while (L <= R) {
            int index = (L + R) / 2;
            if (arr[index] == targetNumber) {
                return index;
            } else if (arr[index] < targetNumber) {
                L = index + 1;
            } else if (arr[index] > targetNumber) {
                R = index - 1;
            }
        }
        return -1;
    }


    public static int binarySearch(int[] arr, int targetNumber) {
        int left = 0;
        int right = arr.length;
        while (left <= right) {
            int index = (left + right) / 2;
            // 等于
            if (arr[index] == targetNumber) {
                return index;
                // 大于
            } else if (arr[index] > targetNumber) {
                right = index;
                // 小于
            } else if (arr[index] < targetNumber) {
                left = index;
            }
        }
        return 0;
    }

    public static void sort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int i1 = i + 1; i1 < arr.length; i1++) {

                if (arr[i] > arr[i1]) {
                    int num = arr[i];
                    arr[i] = arr[i1];
                    arr[i1] = num;
                }
            }
        }
        //  System.err.println(Arrays.toString(arr));
        // return arr;
    }
}
